package com.example.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SmsUtils {
    private static final Logger logger = LoggerFactory.getLogger(SmsUtils.class);

    @Value("${aliyun.sms.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.sms.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.sign-name}")
    private String signName;

    @Value("${aliyun.sms.template-code}")
    private String defaultTemplateCode;
    
    @Value("${aliyun.sms.register-template-code:${aliyun.sms.template-code}}")
    private String registerTemplateCode;
    
    @Value("${aliyun.sms.login-template-code:${aliyun.sms.template-code}}")
    private String loginTemplateCode;
    
    @Value("${aliyun.sms.reset-template-code:${aliyun.sms.template-code}}")
    private String resetTemplateCode;

    /**
     * 发送短信验证码（默认模板）
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendSms(String phone, String code) {
        return sendSms(phone, code, defaultTemplateCode);
    }
    
    /**
     * 发送短信（自定义消息内容，默认模板）
     * @param phone 手机号
     * @param message 消息内容
     * @return 是否发送成功
     */
    public boolean sendSmsWithMessage(String phone, String message) {
        return sendSms(phone, message, defaultTemplateCode);
    }
    
    /**
     * 发送注册验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendRegisterSms(String phone, String code) {
        return sendSms(phone, code, registerTemplateCode);
    }
    
    /**
     * 发送登录验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendLoginSms(String phone, String code) {
        return sendSms(phone, code, loginTemplateCode);
    }
    
    /**
     * 发送重置密码验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendResetSms(String phone, String code) {
        return sendSms(phone, code, resetTemplateCode);
    }

    /**
     * 发送短信
     * @param phone 手机号
     * @param content 内容（验证码或消息）
     * @param templateCode 模板代码
     * @return 是否发送成功
     */
    private boolean sendSms(String phone, String content, String templateCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        
        // 根据模板不同，可能需要调整参数名称
        if (templateCode.equals(defaultTemplateCode) || 
            templateCode.equals(registerTemplateCode) || 
            templateCode.equals(loginTemplateCode) || 
            templateCode.equals(resetTemplateCode)) {
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + content + "\"}");
        } else {
            request.putQueryParameter("TemplateParam", "{\"message\":\"" + content + "\"}");
        }

        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info("短信发送结果: {}, 状态码: {}", response.getData(), response.getHttpStatus());
            return response.getHttpStatus() == 200;
        } catch (ClientException e) {
            logger.error("短信发送失败: {}", e.getMessage());
            return false;
        }
    }
} 